# -*- coding: utf-8 -*-
import inspect

import requests
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QDir, pyqtSignal, QThread, QTimer
from PyQt5.QtGui import QBrush, QColor, QFont, QPalette, QPixmap
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QTableWidgetItem, QPushButton, QHeaderView, QStyle, QHBoxLayout, \
    QCheckBox, QWidget, QFileDialog, QLabel, QApplication
import sys, json

import login
from ImageUploaderThread import ImageUploaderThread
from aysncImageLoader import AsyncImageLoader
from detail import DetailWindow
from add import AddWindow
from ui import main
from utils import api
import constant


class MainWindow(QMainWindow, main.Ui_main):
    token = None
    windowLoaded = pyqtSignal()
    currentTabBtn = None
    currentTabIndex = 0

    def __init__(self, token=''):
        super().__init__()

        self.token = token
        print('MainWindow token: ' + self.token)
        #self.appName = constant.APP_NAME
        #self.apiHost = constant.API_HOST

        self.addWindow = None
        self.detailWindow = None
        self.setupUi(self)

        #设置窗口字体
        self.font = QFont()
        self.font.setFamily("宋体")
        self.font.setPixelSize(10)

        #设置出租列表样式
        self.list_new_zhufang.setFont(self.font)
        self.list_new_zhufang.horizontalHeader().setFont(self.font)
        self.list_new_zhufang.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.list_new_zhufang.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        for i in range(len(self.list_new_zhufang.horizontalHeader())):
            if i != 3:
                self.list_new_zhufang.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)

        # 设置售房列表样式
        self.list_new_shoufang.setFont(self.font)
        self.list_new_shoufang.horizontalHeader().setFont(self.font)
        self.list_new_shoufang.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.list_new_shoufang.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        for i in range(len(self.list_new_shoufang.horizontalHeader())):
            if i != 3:
                self.list_new_shoufang.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)

        #刷新按钮事件
        self.btn_refresh.clicked.connect(lambda: self.switchPage(self.currentTabIndex, self.currentTabBtn))
        #按钮切换页面
        self.btn_index.clicked.connect(lambda: self.switchPage(0, self.btn_index))
        self.btn_zufang.clicked.connect(lambda: self.switchPage(1, self.btn_zufang))
        self.btn_shoufang.clicked.connect(lambda: self.switchPage(1, self.btn_shoufang))
        self.btn_shousuo.clicked.connect(lambda: self.switchPage(2, self.btn_shousuo))
        self.btn_setting.clicked.connect(lambda: self.switchPage(3, self.btn_setting))
        #按钮样式
        self.btn_currentStyle = "QPushButton{color: white;border-color:rgb(110, 102, 157);background-color: rgb(110, 102, 157);}"
        self.btn_defaultStyle = ("QPushButton{height:25px;}"
                                 + "QPushButton:hover{color: white;background-color: rgb(110, 102, 157);"
                                 + "border-color: rgb(110, 102, 157);}")
        self.btn_index.setStyleSheet(self.btn_currentStyle)

        #窗口加载完成后事件
        self.windowLoaded.connect(self.onWindowLoaded)
        QTimer.singleShot(0, lambda: self.windowLoaded.emit())

    #窗口加载完成后执行操作
    def onWindowLoaded(self):
        print("窗口加载完成！")
        self.getZufangData(self.list_new_zhufang)
        self.getShoufangData(self.list_new_shoufang)

    #切换页面
    def switchPage(self, index=0, currentBtn=None):
        print(index, currentBtn)
        if currentBtn is None:
            currentBtn = self.btn_index
        self.stackedWidget_main.setCurrentIndex(index)
        self.currentTabBtn = currentBtn
        self.currentTabIndex = index
        #self.switchBtnStyle(btn)

        #设置按钮默认样式
        btn_nav = self.groupBox_nav.children()
        for b in btn_nav:
            b.setStyleSheet(self.btn_defaultStyle)

        currentBtn.setStyleSheet(self.btn_currentStyle)

        #首页按钮
        if currentBtn == self.btn_index:
            self.getZufangData(self.list_new_zhufang)
            self.getShoufangData(self.list_new_shoufang)
            self.setWindowTitle(constant.APP_NAME)
        #租房 售房 搜索
        elif currentBtn == self.btn_zufang or currentBtn == self.btn_shoufang or currentBtn == self.btn_shousuo:
            self.list_fang.setFont(self.font)
            self.list_fang.horizontalHeader().setFont(self.font)
            self.list_fang.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            self.list_fang.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            for i in range(len(self.list_fang.horizontalHeader())):
                if i != 3:
                    self.list_fang.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)

            if currentBtn == self.btn_zufang:
                title = '租房信息'
            elif currentBtn == self.btn_shoufang:
                title = '售房信息'
            else:
                title = '搜索房源'
            self.label_title.setText(title)
            self.setWindowTitle(constant.APP_NAME + '-' + title)
            self.getShoufangData(self.list_fang)
        #系统设置
        elif currentBtn == self.btn_setting:
            self.list_settingArea.setFont(self.font)
            self.list_settingArea.horizontalHeader().setFont(self.font)
            self.list_settingArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            self.list_settingArea.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            for i in range(len(self.list_settingArea.horizontalHeader()) - 1):
                self.list_settingArea.horizontalHeader().setSectionResizeMode(i, QHeaderView.ResizeToContents)
            self.setWindowTitle(constant.APP_NAME + '-系统设置')
            self.getSettingAreaData(self.list_settingArea)
            self.btn_areaAdd.clicked.connect(self.btn_areaAdd_click)

    def btn_zufangDetail_click(self, id):
        print('id : ' + str(id))
        fun_name = inspect.currentframe().f_code.co_name
        try:
            self.detailWindow = DetailWindow(self.token, id, fun_name)
            self.detailWindow.show()

        except Exception as err:
            print('Main Unexpected error:', sys.exc_info())  # sys.exc_info()返回出错信息

    def btn_shoufangDetail_click(self, id):
        print('id : ' + str(id))
        fun_name = inspect.currentframe().f_code.co_name
        try:
            self.detailWindow = DetailWindow(self.token, id, fun_name)
            self.detailWindow.show()

        except Exception as err:
            print('Main Unexpected error:', sys.exc_info())  # sys.exc_info()返回出错信息

    def btn_areaDetail_click(self, id):
        print(id)
        try:
            fun_name = inspect.currentframe().f_code.co_name
            self.detailWindow = DetailWindow(self.token, id, fun_name)
            self.detailWindow.show()
        except Exception as err:
            print('Main Unexpected error:', sys.exc_info())  # sys.exc_info()返回出错信息

    def btn_areaAdd_click(self):
        try:
            fun_name = inspect.currentframe().f_code.co_name
            self.addWindow = AddWindow(self.token, 0, fun_name)
            self.addWindow.show()

        except Exception as err:
            print('Main Unexpected error:', sys.exc_info())  # sys.exc_info()返回出错信息

    def btn_areaDel_click(self, id):
        print(id)
        try:
            fun_name = inspect.currentframe().f_code.co_name
            self.addWindow = AddWindow(self.token, id, fun_name)
            self.addWindow.show()

        except Exception as err:
            print('Main Unexpected error:', sys.exc_info())  # sys.exc_info()返回出错信息

    def btn_areaEdit_click(self, id):
        print(id)
        try:
            fun_name = inspect.currentframe().f_code.co_name
            self.addWindow = AddWindow(self.token, id, fun_name)
            self.addWindow.window_closed.connect(lambda: self.switchPage(self.currentTabIndex, self.currentTabBtn))
            self.addWindow.show()

        except Exception as err:
            print('btn_areaEdit_click Unexpected error:', sys.exc_info())  # sys.exc_info()返回出错信息

    def getZufangData(self, widget):
        try:
            url = constant.API_HOST + '/list_zufang'
            res = api.get(self, url)
            print(res)

            if res is not None and res['code'] == 0:
                widget.clearContents()
                widget.setRowCount(0)
                # widget.cellDoubleClicked.connect(
                #     lambda row, column: self.cell_clicked(row, column, res))

                for i in range(len(res['data'])):
                    widget.insertRow(i)
                    widget.setItem(i, 0, QTableWidgetItem(str(res['data'][i]['area_name'])))
                    widget.setItem(i, 1, QTableWidgetItem(str(res['data'][i]['house_type'])))
                    widget.setItem(i, 2, QTableWidgetItem(str(res['data'][i]['phone'])))
                    widget.setItem(i, 3, QTableWidgetItem(str(res['data'][i]['remark'])))
                    widget.setItem(i, 4, QTableWidgetItem(str(res['data'][i]['publish_at'])))
                    widget.setItem(i, 5, QTableWidgetItem(str(res['data'][i]['look_times'])))
                    widget.setItem(i, 6, QTableWidgetItem(str(res['data'][i]['like_customer'])))

                    btn_Detail = QPushButton()
                    btn_Detail.setStyleSheet('margin-top:5px;max-height:20px;max-width:60px;border-radius:5px;'
                                             + 'font-size:10px;background-color: rgb(234,160,85)')
                    id = res['data'][i]['id']
                    btn_Detail.setText('查看详情')
                    btn_Detail.clicked.connect(lambda _, id=id: self.btn_zufangDetail_click(id))
                    widget.setCellWidget(i, 7, btn_Detail)

        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

    def getShoufangData(self, widget):
        try:
            url = constant.API_HOST + '/list_shoufang'
            res = api.get(self, url)
            if res is not None and res['code'] == 0:
                widget.clearContents()
                widget.setRowCount(0)
                # widget.cellDoubleClicked.connect(
                #     lambda row, column: self.cell_clicked(row, column, res))
                for i in range(len(res['data'])):
                    widget.insertRow(i)
                    widget.setItem(i, 0, QTableWidgetItem(str(res['data'][i]['area_name'])))
                    widget.setItem(i, 1, QTableWidgetItem(str(res['data'][i]['house_type'])))
                    widget.setItem(i, 2, QTableWidgetItem(str(res['data'][i]['phone'])))
                    widget.setItem(i, 3, QTableWidgetItem(str(res['data'][i]['remark'])))
                    widget.setItem(i, 4, QTableWidgetItem(str(res['data'][i]['publish_at'])))
                    widget.setItem(i, 5, QTableWidgetItem(str(res['data'][i]['look_times'])))
                    widget.setItem(i, 6, QTableWidgetItem(str(res['data'][i]['like_customer'])))

                    btn_Detail = QPushButton()
                    btn_Detail.setStyleSheet('margin-top:5px;max-height:20px;max-width:60px;border-radius:5px;'
                                             + 'font-size:10px;background-color: rgb(234,160,85)')
                    id = res['data'][i]['id']
                    btn_Detail.setText('查看详情')
                    btn_Detail.clicked.connect(lambda _, id=id: self.btn_shoufangDetail_click(id))
                    widget.setCellWidget(i, 7, btn_Detail)

        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

    def getSettingAreaData(self, widget):

        try:
            url = constant.API_HOST + '/setting/list_area_data'
            res = api.get(self, url)
            if res is not None and res['code'] == 0:
                widget.clearContents()
                widget.setRowCount(0)
                # widget.cellDoubleClicked.connect(
                #     lambda row, column: self.cell_clicked(row, column, res))
                for i in range(len(res['data'])):
                    widget.insertRow(i)
                    widget.setItem(i, 0, QTableWidgetItem(str(res['data'][i]['id'])))
                    widget.setItem(i, 1, QTableWidgetItem(str(res['data'][i]['area_name'])))
                    widget.setItem(i, 2, QTableWidgetItem(str(res['data'][i]['area_type'])))
                    widget.setItem(i, 3, QTableWidgetItem(str(res['data'][i]['finish_time'])))
                    widget.setItem(i, 4, QTableWidgetItem(str(res['data'][i]['limit_year'])))
                    widget.setItem(i, 5, QTableWidgetItem(str(res['data'][i]['build_type'])))

                    id = res['data'][i]['id']

                    btn_Detail = QPushButton()
                    btn_Detail.setMinimumWidth(60)
                    btn_Detail.setMinimumHeight(20)
                    btn_Detail.setStyleSheet('margin-right:10px;height:20px;border-radius:5px;'
                                             + 'font-size:10px;background-color: rgb(234,160,85)')
                    btn_Detail.setText('查看详情')
                    btn_Detail.clicked.connect(lambda _, id=id: self.btn_areaDetail_click(id))

                    btn_edit = QPushButton()
                    btn_edit.setMinimumWidth(45)
                    btn_edit.setMinimumHeight(20)
                    btn_edit.setContentsMargins(0, 0, 0, 0)
                    btn_edit.setStyleSheet('height:20px;border-radius:5px;'
                                           + 'font-size:10px;background-color: rgb(234,160,85)')
                    btn_edit.setText('编辑')
                    btn_edit.clicked.connect(lambda _, id=id: self.btn_areaEdit_click(id))

                    btn_del = QPushButton()
                    btn_del.setMinimumWidth(45)
                    btn_del.setMinimumHeight(20)
                    btn_del.setContentsMargins(0, 0, 0, 0)
                    btn_del.setStyleSheet('margin:0;height:20px;border-radius:5px;'
                                          + 'font-size:10px;background-color: rgb(234,160,85)')
                    btn_del.setText('删除')
                    btn_del.clicked.connect(lambda _, id=id: self.btn_areaDel_click(id))

                    layout = QHBoxLayout()
                    layout.setAlignment(Qt.AlignRight)
                    layout.setContentsMargins(0, 0, 0, 0)
                    layout.setSpacing(0)

                    layout.addWidget(btn_Detail)
                    layout.addSpacing(2)
                    layout.addWidget(btn_edit)
                    layout.addSpacing(2)
                    layout.addWidget(btn_del)

                    buttonContainer = QWidget()
                    buttonContainer.setContentsMargins(0, 0, 0, 0)
                    buttonContainer.setLayout(layout)

                    widget.setCellWidget(i, 6, buttonContainer)

        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

    def closeEvent(self, event):
        print("close main")
        if self.token is None:
            app = QApplication.instance()
            app.exit(888)
